# -*- coding: utf-8 -*-
import socket
import numpy as np
import struct
import time
recv_count = 0
print("*********1 Load keras begin  **********************")
from keras.models import load_model
print("*********  Load keras success**********************")

print("*********2 Load keras module  **********************")
new_model = load_model('my_model.h5')
print("*********  Load keras success  ********************")
def predict(x):
    xx = np.array([x])
    x_test = np.reshape(xx, (1, xx.shape[1], 1))

    y_predict = new_model.predict(x_test)
    res = y_predict.tolist()
    #print(x_test, y_predict)
    return res[0][0]

print("*********3 Init server begin  **********************")
serAddress = ('127.0.0.1', 50000)
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(serAddress)
print("*********  Init server ok    **********************")

fo = open("log.txt", "w")

print("*********  \n * \n *\n        server is running now!!!!!!!!!!!!!!!!!!! \n**********************")
while True:
    #print("server is running")
    data, cliAddr = s.recvfrom(2048)
    if not data:
        print("client has exist")
        break
    buf = struct.unpack("IIIII10I", data)
    #print(len(data))
    #print(data)
    msg = buf[5:15]
    #print(msg)
    res = predict(msg)
    ret = int(res+0.5)
    #print(ret)
    print("%d-%d-%d-%d-%d-%d-%d-%d-%d-%d = %d" % (buf[5],buf[6],buf[7],buf[8],buf[9],buf[10],buf[11],buf[12],buf[13],buf[14],ret), file = fo)
    #response the client
    buffer = struct.pack("IIIIII", 2, buf[1], buf[2], buf[3],buf[4], ret)
    #print(buffer)
    recv_count += 1
    if (0 == (recv_count%1000)):
        print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"  num="+str(recv_count))
    s.sendto(buffer, cliAddr)

s.close()
